<template>
	<view class="container bg-white">
		<homeSwiper  :isLoginOn="isLoginOn"></homeSwiper>
		<noticeSwiper :list="noticeList"></noticeSwiper>
		<view class="uni-divider"></view>

		<!-- <recommentMarketList ></recommentMarketList> -->
		<!-- 	<view class="ad">
			<image mode="widthFix" src="../../static/img/ad.jpg"></image>
		</view> -->
		<scroll-view scroll-x class="bg-white nav" scroll-with-animation :scroll-left="scrollLeft">
			<view class="cu-item" :class="index==TabCur?'text-green cur':''" v-for="(item,index) in TabList" :key="index" @tap="tabSelect"
			 :data-id="index">
				{{item}}合约
			</view>
		</scroll-view>
		<view class="uni-divider"></view>
		<view class="uni-column" style="justify-content: center;align-items: center;">
			<view class="qiun-charts">
				<canvas canvas-id="canvasArea" id="canvasArea" class="charts" @touchstart="touchArea"></canvas>
			</view>
			<view class="qiun-charts">
				<canvas canvas-id="canvasMix" id="canvasMix" class="charts" disable-scroll=true @touchstart="touchMix" @touchmove="moveMix"
				 @touchend="touchEndMix"></canvas>
			</view>
			<view class="qiun-charts">
				<canvas canvas-id="canvasLineA" id="canvasLineA" class="charts" @touchstart="touchLineA"></canvas>
			</view>
			<view class="qiun-charts">
				<canvas canvas-id="canvasColumn" id="canvasColumn" class="charts" @touchstart="touchColumn"></canvas>
			</view>
		</view>
		<uni-drawer :visible="drawerVisible" mask="false" mode="left" @close="closeDrawer">
			<settingDrawer :isLoginOn='isLoginOn'></settingDrawer>
		</uni-drawer>
	</view>
</template>

<script>
	import uCharts from '@/js_sdk/u-charts/u-charts/u-charts.js';
	var _self;
	var canvaArea = null;
	var canvaMix = null;
	var canvaLineA = null;
	var canvaColumn = null;
	import {
		mapState,
		mapActions
	} from 'vuex'
	import {
		uniDrawer
	} from '@dcloudio/uni-ui'
	import homeSwiper from '../../components/homeSwiper.vue'
	import noticeSwiper from '../../components/noticeSwiper.vue'
	import recommentMarketList from '../../components/recommentMarketList.vue'
	import marketList from '../../components/marketList.vue'
	import settingDrawer from '../../components/settingDrawer.vue'
	export default {
		data() {
			return {
				noticeList: [],
				marketList: [],
				drawerVisible: false,			
				TabCur: 0,
				scrollLeft: 0,
				TabList: [
					'BTC', 'LTC', 'ETH', 'ETC', 'XRP', 'EOS', 'BCH', 'BSV', 'TRX'
				],
				cWidth: '',
				cHeight: '',
				pixelRatio: 1,
				currentSymbol: 'BTC',
				isLoginOn: false,
				symbolType: 0,
				toast: {
					isShow: false,
					title: '',
					info: '',
					type: ''
				}
			}
		},
		onHide() {
			this.drawerVisible = false;
		},
		onNavigationBarButtonTap(e) {
			console.log('bar button tap')
			this.drawerVisible = !this.drawerVisible;
		},
		onLoad() {
			_self = this
			_self.loadNews()
			// #ifdef APP-PLUS
			plus.push.addEventListener('click', function(msg) {
				uni.switchTab({
					url: "/pages/gendan/shipan"
				})
			}, false);

			plus.push.addEventListener('receive', function(msg) {
				if (plus.os.name === 'iOS') {
					var _msg = msg.payload
				} else {
					var _msg = JSON.parse(msg.payload)
				}

				if (_msg.remote) {
					var options = {
						cover: false,
						title: _msg.mtitle,
						sound: 'system',
						icon: 'icon.png',
						local: true
					};
					plus.push.createMessage(_msg.mcontent, _msg.mpayload, options);

				}

			}, false);
			// #endif
			_self.loadLiguidInfo()
			this.isLoginOn = this.checkLogin()
		},
		components: {
			homeSwiper,
			noticeSwiper,
			recommentMarketList,
			settingDrawer,
			uniDrawer			
		},
		onShow() {
			this.loadNews()
			this.isLoginOn = this.checkLogin()			
			this.toast.isShow = false
		},
		mounted() {
			this.noticeList = ["币胜客种子用户招募中，限时免费体验", "我们一直在做事，请关注我们", "币胜客你的炒币伴侣"];
			this.toast.isShow = false
			uni.$on("freshLogin", this.fresh)
			this.isLoginOn = this.checkLogin()			
			this.loadNews()
		},
		computed: {
			/* ...mapState('home', ['data']),
			content() {
			  return this.data;
			} */
		},
		methods: {
			...mapActions('home', ['getHomeData']),
			/* async initPage() {
			  await this.getHomeData()
			} */

			goBack() {
				console.log('go back')
			},
			changeLoginStatus(event) {
				_self.isLoginOn = event.isLoginOn
				console.log("change strategy :" + _self.strategy)
			},

			tabSelect(e) {
				this.TabCur = e.currentTarget.dataset.id;
				this.scrollLeft = (e.currentTarget.dataset.id - 1) * 60
				_self.currentSymbol = _self.TabList[_self.TabCur]
				_self.loadLiguidInfo()
			},
			closeDrawer() {
				this.drawerVisible = false;
			},
			toLogin() {
				uni.navigateTo({
					url: "../login/login"
				})
			},

			loadLiguidInfo() {

				this.cWidth = uni.upx2px(650);
				this.cHeight = uni.upx2px(500);
				_self.loadLongShortBi()
				_self.loadPosition()
				_self.loadjinYin()
				_self.loadJingYinChicang()
			},

			loadJingYinChicang() {
				//https://www.okex.me/v2/futures/pc/public/getFuturePositionRatio.do?symbol=f_usd_btc&type=0&t=1584932855651
				uni.request({
					url: this.api +
						'/spiders/apis?simpleUrl=https://www.okex.me/v2/futures/pc/public/getFuturePositionRatio.do?t=1584929503298%26symbol=f_usd_' +
						_self.currentSymbol.toLowerCase() + '%26type=' + _self.symbolType,
					method: 'GET',
					success: res => {
						console.log('load jing yin')
						let data = res.data.data.data
						console.log(data)
						let Column = {
							categories: [],
							series: []
						};
						let seriesBuy = {
							name: '多头平均持仓比例',
							data: [],
							color: '#4DB872'
						};
						let seriesSell = {
							name: '空头平均持仓比例',
							data: [],
							color: '#EE6560'
						}

						let cat = []
						for (let item of data.timedata) {
							cat.push(_self.t2dm(item))
						}

						for (let item of data.buydata) {
							seriesBuy.data.push(Number(item * 100).toFixed(2))
						}

						for (let item of data.selldata) {
							seriesSell.data.push(Number(item * 100).toFixed(2))
						}
						Column.categories = cat
						Column.series.push(seriesBuy)
						Column.series.push(seriesSell)
						_self.showColumn("canvasColumn", Column);
					}
				})

			},
			showColumn(canvasId, chartData) {
				canvaColumn = new uCharts({
					$this: _self,
					canvasId: canvasId,
					type: 'column',
					legend: {
						show: true
					},
					fontSize: 11,
					background: '#FFFFFF',
					dataLabel: false,
					dataPointShape: false,
					pixelRatio: _self.pixelRatio,
					animation: true,
					categories: chartData.categories,
					series: chartData.series,
					xAxis: {
						disableGrid: true,
						labelCount: 5,
						format: (val) => {
							return val.toFixed(2)
						}
					},
					yAxis: {
						//disabled:true
						splitNumber: 5,
						disableGrid: true,
						min: 0,
						format: (val) => {
							return val.toFixed(2)
						}
					},

					width: _self.cWidth * _self.pixelRatio,
					height: _self.cHeight * _self.pixelRatio,
					extra: {
						column: {
							type: 'group',
							width: _self.cWidth * _self.pixelRatio * 0.45 / chartData.categories.length
						}
					}
				});

			},
			touchColumn(e) {
				canvaColumn.showToolTip(e, {
					format: function(item, category) {
						if (typeof item.data === 'object') {
							return category + ' ' + item.name + ':' + item.data.value
						} else {
							return category + ' ' + item.name + ':' + item.data
						}
					}
				});
			},

			loadLongShortBi() {
				uni.request({
					url: this.api +
						'/spiders/apis?simpleUrl=https://www.okex.me/v3/futures/pc/market/longShortPositionRatio/' + _self.currentSymbol +
						'?t=1584872642902%26unitType=' + _self.symbolType,
					method: 'GET',
					success: res => {
						console.log('load long shot bi')

						let data = res.data.data.data
						console.log(data)
						let Area = {
							categories: [],
							series: []
						};
						let seriesData = {
							name: '多空持仓人数比',
							data: [],
							color: '#3658B9'
						}

						let cat = []
						for (let item of data.timestamps) {
							cat.push(_self.t2dm(item))
						}

						seriesData.data = data.ratios
						Area.categories = cat
						Area.series.push(seriesData)
						_self.showArea("canvasArea", Area);
					}
				})
			},

			loadPosition() {
				uni.request({
					url: this.api +
						'/spiders/apis?simpleUrl=https://www.okex.me/v3/futures/pc/market/openInterestAndVolume/' + _self.currentSymbol +
						'?t=1584872642902%26unitType=' + _self.symbolType,

					success: function(res) {
						console.log(res.data.data)
						let Mix = {
							categories: [],
							series: []
						};

						let data = res.data.data.data

						let cat = []
						for (let item of data.timestamps) {
							cat.push(_self.t2dm(item))
						}

						let seriesPosition = {
							name: '持仓总量',
							data: [],
							color: '#3658B9',
							type: "line",
							index: 0
						}

						let seriesDeal = {
							name: '交易量',
							data: [],
							color: '#FFBE59',
							type: "column",
							index: 1
						}

						seriesPosition.data = data.openInterests
						seriesDeal.data = data.volumes

						seriesPosition.min = Math.min.apply(Math, seriesPosition.data)
						seriesPosition.max = Math.max.apply(Math, seriesPosition.data)
						seriesDeal.min = Math.min.apply(Math, seriesDeal.data)
						seriesDeal.max = Math.max.apply(Math, seriesDeal.data)
						let avg = (seriesPosition.min + seriesDeal.max) / 2
						seriesPosition.min = avg
						seriesDeal.max = avg

						Mix.series.push(seriesPosition)
						Mix.series.push(seriesDeal)

						Mix.categories = cat;
						console.log('print Mix')
						console.log(Mix)
						_self.showMix("canvasMix", Mix);
					}
				});
			},

			loadjinYin() {
				//https://www.okex.me/v2/futures/pc/public/eliteScale.do?symbol=f_usd_eos&type=0&t=1584929503298

				uni.request({
					url: this.api +
						'/spiders/apis?simpleUrl=https://www.okex.me/v2/futures/pc/public/eliteScale.do?t=1584929503298%26symbol=f_usd_' +
						_self.currentSymbol.toLowerCase() + '%26type=' + _self.symbolType,
					method: 'GET',
					success: res => {
						console.log('load jing yin')
						let data = res.data.data.data
						console.log(data)
						let LineA = {
							categories: [],
							series: []
						};
						let seriesData = {
							name: '多空精英趋势',
							data: [],
							color: '#3658B9'
						}

						let cat = []
						for (let item of data.timedata) {
							cat.push(_self.t2dm(item))
						}

						for (let item of data.buydata) {
							seriesData.data.push(item * 100)
						}
						LineA.categories = cat
						LineA.series.push(seriesData)
						_self.showLineA("canvasLineA", LineA);
					}
				})
			},

			showLineA(canvasId, chartData) {
				canvaLineA = new uCharts({
					$this: _self,
					canvasId: canvasId,
					type: 'line',
					fontSize: 11,
					legend: {
						show: true
					},
					dataLabel: false,
					dataPointShape: false,
					background: '#FFFFFF',
					pixelRatio: _self.pixelRatio,
					categories: chartData.categories,
					series: chartData.series,
					animation: true,
					xAxis: {
						type: 'grid',
						disableGrid: true,
						labelCount: 5
						// gridColor: '#CCCCCC',
						// gridType: 'dash',
						// dashLength: 8
					},
					yAxis: {
						// gridType: 'dash',
						// gridColor: '#CCCCCC',
						// dashLength: 8,
						splitNumber: 5,
						disableGrid: true,
						min: chartData.series[0].min,
						max: chartData.series[0].max,
						format: (val) => {
							return val.toFixed(0)
						}
					},
					width: _self.cWidth * _self.pixelRatio,
					height: _self.cHeight * _self.pixelRatio,
					extra: {
						line: {
							type: 'straight'
						}
					}
				});

			},
			touchLineA(e) {
				canvaLineA.showToolTip(e, {
					format: function(item, category) {
						return category + ' 做多帐户比:' + item.data + '%'
					}
				});
			},

			showMix(canvasId, chartData) {
				canvaMix = new uCharts({
					$this: _self,
					canvasId: canvasId,
					type: 'mix',
					fontSize: 11,
					legend: true,
					background: '#FFFFFF',
					pixelRatio: _self.pixelRatio,
					categories: chartData.categories,
					series: chartData.series,
					animation: true, //是否动画展示
					enableScroll: false, //是否开启图表可拖拽滚动 默认false 支持line, area, column, candle图表类型(需配合绑定@touchstart, @touchmove, @touchend方法)
					xAxis: {
						type: 'grid',
						disableGrid: true,
						labelCount: 5, //X轴可见区域标签数量（即X轴数刻度标签单屏幕限制显示的数量）
						// itemCount: 50,//X轴可见区域数据数量（即X轴数据密度），配合拖拽滚动使用（即仅在启用enableScroll时有效）
						scrollShow: false, //是否显示滚动条，配合拖拽滚动使用（即仅在启用enableScroll时有效）
						scrollAlign: 'left', //滚动条初始位置，left为数据整体左对齐，right为右对齐
					},
					yAxis: {
						data: [{
								min: chartData.series[0].min,
								max: chartData.series[0].max,
								position: 'left',
								format: (val) => {
									return (val / 10000).toFixed(0) + 'w'
								}
							},
							{
								min: chartData.series[1].min,
								max: chartData.series[1].max,
								position: 'right',
								format: (val) => {
									return (val / 1000).toFixed(0) + 'k'
								}
							}
						],
						disableGrid: true,
						splitNumber: 5
					},
					width: _self.cWidth * _self.pixelRatio,
					height: _self.cHeight * _self.pixelRatio,
					dataLabel: false, //是否在图表中显示数据标签内容值
					dataPointShape: false,
					extra: {
						tooltip: {
							bgColor: '#000000',
							bgOpacity: 0.7, //背景颜色透明度
							gridType: 'dash', //辅助线类型（虚线）
							dashLength: 8, //虚线单段长度
							gridColor: '#1890ff',
							fontColor: '#FFFFFF',
							horizentalLine: true, //是否显示横向辅助线
							xAxisLabel: true, //是否显示X轴辅助标签
							yAxisLabel: true, //是否显示Y轴辅助标签
							labelBgColor: '#DFE8FF', //标签背景颜色
							labelBgOpacity: 0.95,
							labelAlign: 'left',
							labelFontColor: '#666666'
						}
					},
				});
			},
			touchMix(e) {
				canvaMix.scrollStart(e);
			},
			moveMix(e) {
				canvaMix.scroll(e);
			},
			touchEndMix(e) {
				canvaMix.scrollEnd(e);
				//下面是toolTip事件，如果滚动后不需要显示，可不填写
				canvaMix.showToolTip(e, {
					format: function(item, category) {
						return category + ' ' + item.name + ':' + item.data
					}
				});
			},
			loadNews() {
				uni.request({
					url: this.api + '/news/list',
					method: 'GET',
					success: res => {
						console.log('load news resp')
						console.log(res)
						if (_self.ifElseReturn(res))
							_self.noticeList = res.data.data
					}
				});
			},
			showArea(canvasId, chartData) {
				canvaArea = new uCharts({
					$this: _self,
					canvasId: canvasId,
					type: 'area',
					fontSize: 11,
					legend: true,
					dataLabel: false,
					dataPointShape: false,
					background: '#021C73',
					pixelRatio: _self.pixelRatio,
					categories: chartData.categories,
					series: chartData.series,
					animation: true,
					xAxis: {
						type: 'grid',
						disableGrid: true,
						labelCount: 5
					},
					yAxis: {
						splitNumber: 6,
						disableGrid: true,
						min: Math.min.apply(Math, chartData.series[0].data),
						max: Math.max.apply(Math, chartData.series[0].data),
						format: (val) => {
							return val.toFixed(2)
						}
					},
					width: _self.cWidth * _self.pixelRatio,
					height: _self.cHeight * _self.pixelRatio,
					extra: {
						area: {
							type: 'straight',
							opacity: 1,
							addLine: true,
							width: 1,
							gradient: true
						}
					}
				});

			},
			touchArea(e) {
				canvaArea.showToolTip(e, {
					format: function(item, category) {
						return category + ' ' + item.name + ':' + item.data
					}
				});
			},	
			
			freshLogin() {
				this.isLoginOn = this.checkLogin()				
			},
			fresh: function() {
				this.freshLogin()
			}
		}
	}
</script>

<style>
	@import "../../colorui/main.css";
	@import "../../colorui/icon.css";

	.uni-common-mt {
		margin-top: 60upx;
		position: relative;
	}

	.info {
		position: absolute;
		right: 20upx;
	}

	.ad image {
		min-height: 100%;
		min-width: 100%;
	}

	.rank-title {
		padding: 20px 20px;
	}

	.login-banner {
		background-color: #000207;
		display: flex;
		flex-direction: row;
		justify-content: flex-end;
	}

	.login-button {
		color: #F2F2F9;
		display: flex;
		padding-right: 50upx;
		font-size: 20upx;
		padding-top: 10upx;
	}

	.qiun-charts {
		width: 650upx;
		height: 500upx;
		background-color: #FFFFFF;
		display: inline-flex;
	}

	.charts {
		width: 650upx;
		height: 500upx;
		background-color: #FFFFFF;
	}
</style>
